package com.itcam.socket_.udp_;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * Author:Cammy.Wu
 * Date:2024-05-15
 * Description:双向通信——发送方
 */

public class SendDemo02 {
    public static void main(String[] args) throws IOException {
        System.out.println("袁大帅上线了...");
        // 1.准备套接字：指定发送方的端口号
        DatagramSocket datagramSocket = new DatagramSocket(8989);
        // 2.准备数据包
//        String str = "你欲何为";
        Scanner sc = new Scanner(System.in);
        System.out.print("袁天罡：");
        String str = sc.next();
        byte[] bytes = str.getBytes();

        /**
         * 需要四个参数：
         *      1.指的是传送数据转为字节数组
         *      2.字节数组的长度
         *      3.封装接收方的ip
         *      4.指定接收方的端口号
         */
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("localhost"), 8990);
        // 发送
        datagramSocket.send(datagramPacket);

        // 接受李星云的回复
        byte[] b = new byte[1024];
        DatagramPacket datagramPacket_ = new DatagramPacket(b, b.length);
        datagramSocket.receive(datagramPacket_);

        // 取出数据
        byte[] data = datagramPacket_.getData();
        String s = new String(data, 0, datagramPacket_.getLength());
        System.out.println("李星云对我说：" + s);

        // 关闭资源
        datagramSocket.close();
    }
}
